package com.suyang.syt.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suyang.syt.dao.interfaces.RoleDao;
import com.suyang.syt.dao.interfaces.UserDao;
import com.suyang.syt.dao.interfaces.UserRoleDao;
import com.suyang.syt.model.Role;
import com.suyang.syt.model.User;
import com.suyang.syt.model.UserRole;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.model.dto.PagerEasyUI;
import com.suyang.syt.model.dto.UserRoleDTO;
import com.suyang.syt.service.interfaces.UserRoleService;
import com.suyang.syt.util.EmptyUtil;

@Service
public class UserRoleServiceImpl implements UserRoleService {
	@Autowired
	private UserRoleDao userRoleDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;

	@Override
	public PagerEasyUI<UserRoleDTO> listByEasyUI(int flag, long objid, int page, int rows, String sort, String order) throws Exception {
		// 1、拼接查询语句
		StringBuilder hql = new StringBuilder(" from UserRole ur where 1=1 ");
		if (objid != 0) {
			switch (flag) {
			case 1:
				hql.append(" and ur.userId=").append(objid);
				break;
			case 2:
				hql.append(" and ur.roleId=").append(objid);
				break;
			}
		}
		if (EmptyUtil.isNotEmpty(sort)) {
			hql.append(" order by ur.").append(sort);
		}
		if (EmptyUtil.isNotEmpty(order)) {
			hql.append(" ").append(order);
		}
		PagerEasyUI<UserRoleDTO> easyUIPager = new PagerEasyUI<UserRoleDTO>();
		// 2、获取用户easyUI数据
		List<UserRole> userRoles = userRoleDao.findByEasyUI(hql.toString(), page, rows);
		// 3、转换用户数据
		List<UserRoleDTO> datas = new ArrayList<UserRoleDTO>();
		UserRoleDTO userRoleDTO = null;
		User user = null;
		Role role = null;
		for (UserRole userRole : userRoles) {
			userRoleDTO = new UserRoleDTO(userRole);
			user = userDao.load(userRole.getUserId());
			if (user != null) {
				userRoleDTO.setUserName(user.getUsername());
			}
			role = roleDao.load(userRole.getRoleId());
			if (role != null) {
				userRoleDTO.setRoleName(role.getName());
			}
			datas.add(userRoleDTO);
		}
		easyUIPager.setRows(datas);
		easyUIPager.setTotal((Long) userRoleDao.queryByHql(" select count(*) " + hql.substring(0, hql.indexOf("order by"))));
		return easyUIPager;
	}

	@Override
	public AjaxObj deletes(String ids) throws Exception {
		userRoleDao.deletes(ids);
		return new AjaxObj();
	}

	@Override
	public AjaxObj add(UserRole userRole) throws Exception {
		if (userRole.getUserId() <= 0) {
			return new AjaxObj(0, "添加错误,用户ID不能为空!");
		}
		if (userRole.getRoleId() <= 0) {
			return new AjaxObj(0, "添加错误,角色ID不能为空!");
		}
		if (userRoleDao.countUserRole(userRole.getUserId(), userRole.getRoleId()) > 0) {
			return new AjaxObj(0, "用户已经添加了角色,不能重复添加!");
		}
		userRoleDao.add(userRole);
		return new AjaxObj();
	}
}
